package com.fullstack.landscape.editor;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.RuntimeUtil;
import com.fullstack.landscape.editor.gui.MainFXView;
import com.spring4all.swagger.EnableSwagger2Doc;
import de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport;
import javafx.stage.Stage;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import static org.slf4j.LoggerFactory.getLogger;

@SpringBootApplication
@EnableSwagger2Doc
public class LandscapeEditorApplication extends AbstractJavaFxApplicationSupport {

    /**
     * logger
     */
    private static final Logger log = getLogger(LandscapeEditorApplication.class);


    public static void main(String[] args) {
        System.setProperty("-Djava.net.preferIPv4Stack", "true");
        System.setProperty("-Dfile.encoding", "UTF-8");
        boolean isRunning = checkApplicationIsRunning();
        if (isRunning) {
            log.debug("application already running");
            LandscapeEditorApplication.openChrome();
        } else {
            launch(LandscapeEditorApplication.class, MainFXView.class, args);
        }
    }

    @Override
    public void start(Stage stage) throws Exception {
        super.start(stage);
        stage.setResizable(false);
    }

    /**
     * 监测系统端口是否被占用
     *
     * @return
     */
    public static boolean checkApplicationIsRunning() {
        boolean isRunning = !NetUtil.isUsableLocalPort(8080);
        log.debug("isRunning:" + isRunning);
        return isRunning;
    }

    public static void openChrome() {
        String cmd = "cmd.exe /c start chrome http://localhost:8080/index.html";
        String firefoxCmd = "cmd.exe /c start firefox 127.0.0.1:8080/index.html";
        RuntimeUtil.execForStr(cmd);
    }

}
